import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Sever {
    private DatagramSocket socket = null;

    public Sever (int port) throws SocketException {
        //构造socket的同时关联端口
        socket = new DatagramSocket(port);
    }

    private String process(String request){
        //不做处理
        return request;
    }

    public void start() throws IOException {
        //循环三件事//
        //1.读请求并解析
        //2.根据请求算响应
        //3.送回客户端
        while (true){
            System.out.println("服务器启动！");
            DatagramPacket Requestpacket = new DatagramPacket(new byte[4096],4096);//创建空的packet对象
            //读取客户端请求
            socket.receive(Requestpacket);//参数作为返回值，传一个空的pocket对象，由receive来填充
            //方便处理请求转成String
            String request = new String(Requestpacket.getData(),Requestpacket.getLength());
            //计算请求
            String response = process(request);
            //打包响应(包括写回端口的IP号和端口号)
            DatagramPacket responsaPacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    Requestpacket.getSocketAddress());
            //送出响应
            socket.send(responsaPacket);
            System.out.printf("[%s:%d] req: %s, resp: %s\n", Requestpacket.getAddress().toString(),
                    Requestpacket.getPort(), request, response);
            //服务器pass·
          }
        }


    public static void main(String[] args) throws IOException {
        Sever udpEchoServer = new Sever(9090);
        udpEchoServer.start();
    }

}
